/*
 * @(#)FdService.java Apr 30, 2007
 * 
 * Copyright 2007 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */
package com.cnc.fd.service;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cnc.bas.db.HiberDao;
import com.cnc.bas.db.JdbcDao;
import com.cnc.bas.util.Log;
import com.cnc.fd.Constants;
 
import com.cnc.fd.hiber.FdFile;
import com.cnc.fd.hiber.FdManualTask;
import com.cnc.fd.hiber.FdTaskDetail;
import com.cnc.fd.hiber.FdTaskList; 
import com.cnc.fd.sqlmapDao.IActionLogSqlDao;
import com.cnc.fd.util.UuidGenerator;


/**
 * @author 阿闲
 * @date   Apr 30, 2007
 * @version 1.0
 */
public class FdServiceImpl implements IFdService {	
	
	private HiberDao hiberDao;
	private JdbcDao jdbcDao;
	private FdDao fdDao;
	private IActionLogSqlDao actionLogDao;
	protected  Log log = Log.getLogger(this.getClass());
	
	public IActionLogSqlDao getActionLogDao() {
		return actionLogDao;
	}

	public void setActionLogDao(IActionLogSqlDao actionLogDao) {
		this.actionLogDao = actionLogDao;
	}

	 
	
	public void setFdDao(FdDao fsDao) {
		this.fdDao = fsDao;
	}
	
	public void setHiberDao(HiberDao hiberDao) {
		this.hiberDao = hiberDao;
	}	

	public void setJdbcDao(JdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}
  
	/**
	 * 目标服务器同步开始
	 * @param taskId
	 * @param ip
	 */
	public void updateServerSyncStart(String taskId, String ip, String sourceIp){
		String sql = "update FD_Task_Detail set syncStatus=?, syncStartTime=?, sourceIp=? where taskId=? and ip=?";
		Object[] values = {Constants.SYNC_STATUS_CUR_SYNC, new Date(), sourceIp, taskId, ip};
		jdbcDao.update(sql, values);
	}
	/**
	 * 目标服务器同步结束
	 * @param taskId
	 * @param ip
	 * @param syncStatus  成功或失败
	 */
	public void updateServerSyncEnd(String taskId, String ip, String syncStatus, String errorno){
		
		if(errorno == null) errorno = "0";			
		String sql = "update FD_Task_Detail set syncStatus=?, syncEndTime=?, errorno=? where taskId=? and ip=?";
		Object[] values = {syncStatus, new Date(), errorno,taskId, ip};
		jdbcDao.update(sql, values);
	}
	
	/**
	 * 某次同步失败后，初始化目标机器的状态
	 * 对于某台机器，如果结束时间大于开始时间，那么肯定是超时过
	 * @param taskId
	 * @param ip
	 */
	public void initServerSyncStatus(String taskId, String ip){
		String sql = "update FD_Task_Detail set syncStatus=?, syncEndTime=? where taskId=? and ip=?";
		Object[] values = {Constants.SYNC_STATUS_UN_SYNC, new Date(), taskId, ip};
		jdbcDao.update(sql, values);
	}
	
	/**
	 * 更新任务列表的任务状态(任务结束)
	 * @param taskId
	 * @param taskStatus
	 */
	public void updateTaskEndStatus(String taskId, String taskStatus){
		
		String sql = "update FD_Task_List set taskStatus=?, syncEndTime=? where taskId=?";
		Object[] values = {taskStatus, new Date(), taskId};
		jdbcDao.update(sql, values);
		
		if(taskStatus.equals(Constants.TASK_STATUS_STOP)){
			fdDao.updatePreTaskStop(taskId);
		}
	}
	
	/**
	 * 创建同步机器的任务明细
	 */
	public void createSyncMachineTaskDetail(String taskId, String sourceIp, String targetIp){
		List<String> enternames = fdDao.getEnternamesByServerIp(sourceIp);
		boolean isUploadServer = fdDao.isUploadServer(targetIp);
		for(int i=0; i<enternames.size(); i++){
			FdManualTask task = new FdManualTask();
			task.setEntername(enternames.get(i));
			task.setSourceip(sourceIp);
			task.setTargetip(targetIp);
			task.setTimestamp(new Date());
			task.setTaskstatus(Constants.TASK_STATUS_WAIT);
			task.setTaskkind(Constants.TASK_KIND_SYNCCUSTOMNER);
			task.setParenttask(taskId);
			hiberDao.save(task);
			if(!isUploadServer && Constants.IS_NEED_TEMP_DIR.equals("yes")){
				FdManualTask renameTask = new FdManualTask();
				renameTask.setPretask(task.getTaskid());
				renameTask.setEntername(enternames.get(i));
				renameTask.setSourceip(sourceIp);
				renameTask.setTargetip(targetIp);
				renameTask.setTimestamp(new Date());
				renameTask.setTaskstatus(Constants.TASK_STATUS_SUSPEND);
				renameTask.setTaskkind(Constants.TASK_KIND_RENAME);
				renameTask.setParenttask(taskId);
			}
		}
	}	
	
	 
 
	public void addHibernateObj(Object vo){	    
	    hiberDao.save(vo);
	}
	
	public Object loadHibernateObj(Class server,Serializable pk){
	    return hiberDao.load(server, pk);
	}
	
	public Object getHibernateObj(Class server,Serializable pk){
        return hiberDao.get(server, pk);
    }
	
	public void updateHibernateObj(Object vo){
	    hiberDao.saveOrUpdate(vo);	    
	}
	
	public void deleteHibernateObj(Object vo){
	    hiberDao.delete(vo);   
	}
	
	public List getHibernateObj(String hql){
	    return hiberDao.find(hql);
	}

	
	public void batchDeleteSyncFile(HashMap map) {
		// TODO Auto-generated method stub
		
		StringBuffer sql=new StringBuffer();
		StringBuffer condition=new StringBuffer();
		if (0!=map.size()||null != map.get("entername") || null != map.get("taskKind")
				|| null != map.get("taskStatus") || null != map.get("filename")
				|| null != map.get("sourceIp") || null != map.get("startDate")
				|| null != map.get("endDate")) {
			sql.append("DELETE FROM FD_Task_List WHERE 1=1");
			if (null != map.get("entername")) {
				condition.append(" and entername='"+map.get("entername").toString()+"'");
			}
			if (null != map.get("taskKind")) {
				condition.append(" and taskKind='"+map.get("taskKind").toString()+"'");
			}
			if (null != map.get("taskStatus")) {
				if("run".equals(map.get("taskStatus").toString())||"wait".equals(map.get("taskStatus").toString()))
					return ;
				condition.append(" and taskStatus ='"
						+ map.get("taskStatus").toString()+"'");
			} else {
				condition.append(" and taskStatus not in ('wait','run')");
			}

			if (null != map.get("filename")) {
				condition.append(" and filename like '%"+map.get("filename").toString()+"%'");
			}
			if (null != map.get("sourceIp")) {
				condition.append(" and sourceIp like '%"+map.get("sourceIp").toString()+"%'");
			}
			if (null != map.get("startDate")) {
				condition.append(" and timestamp>=?");
			}
			if (null != map.get("endDate")) {
				condition.append(" and timestamp <=?");
			}
		}else{
			return;
		}
		log.logDebug(sql.toString()+condition.toString());
		this.jdbcDao.execute("delete from FD_Task_Detail where taskId in (select taskId from FD_Task_List where 1=1 "
						+ condition.toString() + ")");
		this.jdbcDao.execute(sql.toString() + condition.toString());
	}


	public void batchUpdateSyncFile(HashMap map) {
		// TODO Auto-generated method stub

		StringBuffer sql=new StringBuffer();
		StringBuffer condition=new StringBuffer();
		if (null != map.get("entername") || null != map.get("taskKind")
				|| null != map.get("taskStatus") || null != map.get("filename")
				|| null != map.get("sourceIp") || null != map.get("startDate")
				|| null != map.get("endDate")) {
			sql.append("update FD_Task_List set taskStatus='"+map.get("changeStatus").toString()+"' WHERE 1=1");
			if (null != map.get("entername")) {
				condition.append(" and entername='"+map.get("entername").toString()+"'");
			}
			if (null != map.get("taskKind")) {
				condition.append(" and taskKind='"+map.get("taskKind").toString()+"'");
			}
			if (null != map.get("taskStatus")) {
				condition.append(" and taskStatus ='"
						+ map.get("taskStatus").toString()+"'");
			}
			if (null != map.get("filename")) {
				condition.append(" and filename like '%"+map.get("filename").toString()+"%'");
			}
			if (null != map.get("sourceIp")) {
				condition.append(" and sourceIp like '%"+map.get("sourceIp").toString()+"%'");
			}
			if (null != map.get("startDate")) {
				condition.append(" and timestamp>=?");
			}
			if (null != map.get("endDate")) {
				condition.append(" and timestamp <=?");
			}
		}else{
			return;
		}
		log.logDebug(sql.toString()+condition.toString());
		if ("wait".equals(map.get("changeStatus").toString())) {
			this.jdbcDao
					.execute("delete from FD_Task_Detail where taskId in (select taskId from FD_Task_List where 1=1 "
							+ condition.toString() + ")");
		}
		this.jdbcDao.execute(sql.toString()+condition.toString());
		//置为success的任务要重新发送同步完成回馈
		if("success".equals(map.get("changeStatus").toString())){
			String tmp="update FD_Task_List set isReport='"+Constants.IS_REPORT_N+"' where 1=1 "+condition.toString();
			log.logDebug(tmp);
			jdbcDao.execute(tmp);
		}
	}
	
	public void addActionLog(HashMap log) {
		// TODO Auto-generated method stub
		log.put("UUID", UuidGenerator.getUuid());
		log.put("ACTION_TIME", new Date());
		this.actionLogDao.addActionLog(log);
	}

	public void deleteActionLog(String id) {
		// TODO Auto-generated method stub
		this.actionLogDao.deleteActionLogById(id);
	}

	public List getActionLog(HashMap condition) {
		// TODO Auto-generated method stub
		return this.actionLogDao.getActionLog(condition);
	}
	
}


